"""
用户认证相关API - 集成Supabase
"""
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, EmailStr
from datetime import datetime, timedelta
from typing import Dict, Any, Optional
import jwt
import os
import logging
import random
import string
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from supabase import create_client, Client
from gotrue.errors import AuthApiError

router = APIRouter()
security = HTTPBearer()

# 配置日志
logger = logging.getLogger(__name__)

# Supabase配置
SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY")

if not SUPABASE_URL or not SUPABASE_SERVICE_KEY:
    logger.warning("Supabase配置缺失，使用本地认证模式")
    supabase: Optional[Client] = None
else:
    try:
        supabase: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
        logger.info("✅ Supabase客户端初始化成功")
    except Exception as e:
        logger.error(f"❌ Supabase客户端初始化失败: {e}")
        supabase = None

# JWT配置
SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key-change-in-production")
SUPABASE_JWT_SECRET = os.getenv("SUPABASE_JWT_SECRET", SECRET_KEY)
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 1440  # 24小时

# 邮件配置
SMTP_SERVER = os.getenv("SMTP_SERVER", "smtp.gmail.com")
SMTP_PORT = int(os.getenv("SMTP_PORT", "587"))
SMTP_USERNAME = os.getenv("SMTP_USERNAME", "")
SMTP_PASSWORD = os.getenv("SMTP_PASSWORD", "")
FROM_EMAIL = os.getenv("FROM_EMAIL", SMTP_USERNAME)

# 验证码存储（生产环境应使用Redis）
verification_codes = {}

# 数据模型
class UserLogin(BaseModel):
    email: EmailStr
    password: str

class UserRegister(BaseModel):
    username: str
    email: EmailStr
    password: str
    confirm_password: str

class EmailVerificationRequest(BaseModel):
    email: EmailStr

class EmailVerificationConfirm(BaseModel):
    email: EmailStr
    verification_code: str

class Token(BaseModel):
    access_token: str
    token_type: str
    expires_in: int
    user_id: str
    user: Optional[Dict[str, Any]] = None

class User(BaseModel):
    user_id: str
    username: Optional[str] = None
    email: str
    created_at: str
    preferences: Optional[Dict[str, Any]] = None
    display_name: Optional[str] = None
    avatar_url: Optional[str] = None

# 工具函数
def generate_verification_code() -> str:
    """生成6位数字验证码"""
    return ''.join(random.choices(string.digits, k=6))

def send_verification_email_via_supabase(email: str, verification_code: str) -> bool:
    """使用Supabase发送验证码邮件"""
    if not supabase:
        logger.error("❌ Supabase客户端不可用，无法发送邮件")
        return False
    
    try:
        logger.info(f"📧 开始使用Supabase发送验证码邮件: {email}")
        
        # 使用Supabase的邮件模板功能
        # 注意：这需要在Supabase后台配置邮件模板
        email_template = f"""
        <div style="max-width: 600px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif;">
            <h2 style="color: #4CAF50; text-align: center;">OrientDirector 邮箱验证</h2>
            <p>您好！</p>
            <p>您正在注册OrientDirector账户，请使用以下验证码完成邮箱验证：</p>
            <div style="background-color: #f5f5f5; padding: 20px; text-align: center; margin: 20px 0; border-radius: 8px;">
                <h1 style="color: #4CAF50; font-size: 32px; margin: 0; letter-spacing: 5px;">{verification_code}</h1>
            </div>
            <p>验证码有效期为10分钟，请及时使用。</p>
            <p>如果您没有注册OrientDirector账户，请忽略此邮件。</p>
            <hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
            <p style="color: #666; font-size: 12px; text-align: center;">
                此邮件由OrientDirector系统自动发送，请勿回复。
            </p>
        </div>
        """
        
        # 方法1：尝试使用Supabase Admin API发送邮件
        try:
            # 创建一个临时用户来触发邮件发送
            logger.info(f"🔧 尝试通过Supabase Admin API发送邮件: {email}")
            
            # 使用Supabase的邮件发送功能
            # 注意：这需要在Supabase项目中启用邮件功能
            response = supabase.auth.admin.invite_user_by_email(
                email,
                {
                    "data": {
                        "verification_code": verification_code,
                        "email_type": "verification",
                        "app_name": "OrientDirector"
                    }
                }
            )
            
            logger.info(f"✅ Supabase邮件发送成功: {email}, 响应: {response}")
            return True
            
        except Exception as supabase_error:
            logger.warning(f"⚠️ Supabase Admin API发送失败，尝试备用方案: {supabase_error}")
            
            # 方法2：备用方案 - 使用自定义SMTP（如果配置了）
            if SMTP_USERNAME and SMTP_PASSWORD:
                logger.info(f"🔄 使用SMTP备用方案发送邮件: {email}")
                return send_verification_email_smtp(email, verification_code)
            else:
                logger.error(f"❌ 没有可用的邮件发送方案: {email}")
                return False
        
    except Exception as e:
        logger.error(f"❌ Supabase邮件发送过程中发生错误: {e}")
        
        # 备用方案
        if SMTP_USERNAME and SMTP_PASSWORD:
            logger.info(f"🔄 使用SMTP备用方案: {email}")
            return send_verification_email_smtp(email, verification_code)
        
        return False

def send_verification_email_smtp(email: str, verification_code: str) -> bool:
    """SMTP备用邮件发送方案"""
    if not SMTP_USERNAME or not SMTP_PASSWORD:
        logger.error("❌ SMTP配置缺失，无法发送邮件")
        return False
    
    try:
        logger.info(f"📧 使用SMTP发送验证码邮件: {email}")
        
        # 创建邮件内容
        msg = MIMEMultipart()
        msg['From'] = FROM_EMAIL
        msg['To'] = email
        msg['Subject'] = "OrientDirector - 邮箱验证码"
        
        # 邮件正文
        body = f"""
        <html>
        <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
            <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                <h2 style="color: #4CAF50;">OrientDirector 邮箱验证</h2>
                <p>您好！</p>
                <p>您正在注册OrientDirector账户，请使用以下验证码完成邮箱验证：</p>
                <div style="background-color: #f5f5f5; padding: 20px; text-align: center; margin: 20px 0; border-radius: 8px;">
                    <h1 style="color: #4CAF50; font-size: 32px; margin: 0; letter-spacing: 5px;">{verification_code}</h1>
                </div>
                <p>验证码有效期为10分钟，请及时使用。</p>
                <p>如果您没有注册OrientDirector账户，请忽略此邮件。</p>
                <hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
                <p style="color: #666; font-size: 12px;">
                    此邮件由OrientDirector系统自动发送，请勿回复。
                </p>
            </div>
        </body>
        </html>
        """
        
        msg.attach(MIMEText(body, 'html', 'utf-8'))
        
        # 发送邮件
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()
            server.login(SMTP_USERNAME, SMTP_PASSWORD)
            server.send_message(msg)
        
        logger.info(f"✅ SMTP验证码邮件发送成功: {email}")
        return True
        
    except Exception as e:
        logger.error(f"❌ SMTP发送验证码邮件失败: {e}")
        return False

def send_verification_email(email: str, verification_code: str) -> bool:
    """统一的验证码邮件发送接口"""
    logger.info(f"📧 开始发送验证码邮件: {email}, 验证码: {verification_code}")
    
    # 优先使用Supabase邮件服务
    success = send_verification_email_via_supabase(email, verification_code)
    
    if not success:
        logger.warning(f"⚠️ Supabase邮件发送失败，尝试SMTP备用方案: {email}")
        success = send_verification_email_smtp(email, verification_code)
    
    if success:
        logger.info(f"✅ 验证码邮件发送成功: {email}")
    else:
        logger.error(f"❌ 所有邮件发送方案都失败了: {email}")
    
    return success

def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
    """创建访问令牌"""
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

def verify_supabase_token(token: str) -> Optional[Dict]:
    """验证Supabase JWT令牌"""
    if not supabase:
        return None
    
    try:
        # 方法1: 直接解析JWT令牌（推荐方式）
        import jwt as pyjwt
        
        # 首先尝试使用Supabase JWT Secret验证
        try:
            # 使用Supabase JWT Secret验证令牌
            payload = pyjwt.decode(
                token, 
                SUPABASE_JWT_SECRET, 
                algorithms=["HS256"],
                audience="authenticated",  # Supabase默认audience
                options={"verify_aud": False}  # 暂时禁用audience验证以避免错误
            )
            logger.info(f"JWT payload: {payload}")
            
            # 验证必要字段
            if payload.get('sub') and payload.get('email'):
                # 检查令牌是否过期
                exp = payload.get('exp')
                if exp and datetime.fromtimestamp(exp) < datetime.now():
                    logger.warning("令牌已过期")
                    return None
                
                return {
                    "user_id": payload.get('sub'),
                    "email": payload.get('email'),
                    "created_at": payload.get('created_at', datetime.now().isoformat())
                }
        except Exception as jwt_error:
            logger.error(f"JWT解析失败: {jwt_error}")
            
        # 如果上面失败，尝试不验证签名解析（用于调试）
        try:
            payload = pyjwt.decode(token, options={"verify_signature": False})
            logger.info(f"JWT payload (无签名验证): {payload}")
            
            # 验证必要字段
            if payload.get('sub') and payload.get('email'):
                # 检查令牌是否过期
                exp = payload.get('exp')
                if exp and datetime.fromtimestamp(exp) < datetime.now():
                    logger.warning("令牌已过期")
                    return None
                
                return {
                    "user_id": payload.get('sub'),
                    "email": payload.get('email'),
                    "created_at": payload.get('created_at', datetime.now().isoformat())
                }
        except Exception as jwt_error:
            logger.error(f"JWT解析失败（无签名验证）: {jwt_error}")
        
        # 方法2: 使用Supabase客户端验证（备用方式）
        try:
            # 创建一个临时的Supabase客户端来验证令牌
            from supabase import create_client
            temp_supabase = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
            
            # 尝试使用令牌获取用户信息
            headers = {"Authorization": f"Bearer {token}"}
            response = temp_supabase.auth.get_user(token)
            
            if response and response.user:
                return {
                    "user_id": response.user.id,
                    "email": response.user.email,
                    "created_at": response.user.created_at
                }
        except Exception as supabase_error:
            logger.error(f"Supabase验证失败: {supabase_error}")
    
    except Exception as e:
        logger.error(f"令牌验证过程中发生错误: {e}")
    
    return None

async def get_or_create_user_profile(user_id: str, email: str, username: Optional[str] = None) -> Dict:
    """获取或创建用户配置文件"""
    if not supabase:
        return {
            "user_id": user_id,
            "email": email,
            "username": username or email.split('@')[0],
            "created_at": datetime.now().isoformat(),
            "preferences": {}
        }
    
    try:
        # 查询用户配置文件
        result = supabase.table('users').select('*').eq('id', user_id).execute()
        
        if result.data:
            user_data = result.data[0]
            return {
                "user_id": user_data['id'],
                "email": user_data['email'],
                "username": user_data.get('display_name') or username or email.split('@')[0],
                "created_at": user_data['created_at'],
                "preferences": user_data.get('preferences', {}),
                "display_name": user_data.get('display_name'),
                "avatar_url": user_data.get('avatar_url')
            }
        else:
            # 创建新的用户配置文件
            new_user = {
                "id": user_id,
                "email": email,
                "display_name": username or email.split('@')[0],
                "preferences": {},
                "created_at": datetime.now().isoformat(),
                "updated_at": datetime.now().isoformat()
            }
            
            result = supabase.table('users').insert(new_user).execute()
            if result.data:
                user_data = result.data[0]
                return {
                    "user_id": user_data['id'],
                    "email": user_data['email'],
                    "username": user_data.get('display_name'),
                    "created_at": user_data['created_at'],
                    "preferences": user_data.get('preferences', {}),
                    "display_name": user_data.get('display_name'),
                    "avatar_url": user_data.get('avatar_url')
                }
    except Exception as e:
        logger.error(f"用户配置文件操作失败: {e}")
    
    # 降级到基本用户信息
    return {
        "user_id": user_id,
        "email": email,
        "username": username or email.split('@')[0],
        "created_at": datetime.now().isoformat(),
        "preferences": {}
    }

@router.post("/login", response_model=Token)
async def login(user_credentials: UserLogin):
    """用户登录 - 使用Supabase认证"""
    if not supabase:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="认证服务不可用"
        )
    
    try:
        logger.info(f"🔐 尝试登录用户: {user_credentials.email}")
        
        # 使用Supabase进行认证
        response = supabase.auth.sign_in_with_password({
            "email": user_credentials.email,
            "password": user_credentials.password
        })
        
        if not response.user or not response.session:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="邮箱或密码错误",
                headers={"WWW-Authenticate": "Bearer"},
            )
        
        user = response.user
        session = response.session
        
        logger.info(f"✅ 用户登录成功: {user.email} (ID: {user.id})")
        
        # 获取或创建用户配置文件
        user_profile = await get_or_create_user_profile(
            user.id, 
            user.email,
            user.user_metadata.get('username') if user.user_metadata else None
        )
        
        # 创建自定义JWT令牌（可选，也可以直接使用Supabase的access_token）
        access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
        access_token = create_access_token(
            data={"sub": user.id, "email": user.email},
            expires_delta=access_token_expires
        )
        
        return {
            "access_token": session.access_token,  # 使用Supabase的access_token
            "token_type": "bearer",
            "expires_in": ACCESS_TOKEN_EXPIRE_MINUTES * 60,
            "user_id": user.id,
            "user": user_profile
        }
        
    except AuthApiError as e:
        logger.error(f"❌ Supabase认证错误: {e}")
        error_message = str(e).lower()
        
        if "invalid login credentials" in error_message or "invalid credentials" in error_message:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="邮箱或密码错误",
                headers={"WWW-Authenticate": "Bearer"},
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="认证失败，请检查登录信息",
                headers={"WWW-Authenticate": "Bearer"},
            )
    except Exception as e:
        logger.error(f"❌ 登录过程中发生错误: {e}")
        error_message = str(e).lower()
        
        # 检查是否是凭据相关错误
        if ("invalid login credentials" in error_message or 
            "invalid credentials" in error_message or
            "authentication" in error_message):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="邮箱或密码错误",
                headers={"WWW-Authenticate": "Bearer"},
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="登录服务暂时不可用"
            )

@router.post("/send-verification-code")
async def send_verification_code(email_data: EmailVerificationRequest):
    """发送邮箱验证码"""
    email = email_data.email
    
    # 生成验证码
    verification_code = generate_verification_code()
    
    # 存储验证码（包含过期时间）
    verification_codes[email] = {
        "code": verification_code,
        "expires_at": datetime.now() + timedelta(minutes=10),
        "attempts": 0
    }
    
    # 发送验证码邮件
    logger.info(f"📧 准备重新发送验证码: {email}, 验证码: {verification_code}")
    email_sent = send_verification_email(email, verification_code)
    
    if email_sent:
        logger.info(f"✅ 验证码重新发送成功: {email}")
    else:
        logger.error(f"❌ 验证码重新发送失败: {email}")
        # 如果邮件发送失败，仍然返回成功（为了安全考虑）
        logger.warning(f"⚠️ 验证码邮件发送失败，但返回成功响应: {email}")
    
    logger.info(f"📧 验证码已生成并尝试发送: {email}")
    
    return {
        "message": "验证码已发送到您的邮箱",
        "email": email,
        "expires_in": 600,  # 10分钟
        "note": "请检查您的邮箱（包括垃圾邮件文件夹）并输入6位数字验证码"
    }

@router.post("/register", response_model=Dict[str, Any])
async def register(user_data: UserRegister):
    """用户注册 - 第一步：验证用户信息并发送验证码"""
    # 验证密码确认
    if user_data.password != user_data.confirm_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="两次输入的密码不一致"
        )
    
    # 验证密码长度
    if len(user_data.password) < 6:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="密码长度至少为6位"
        )
    
    # 检查邮箱是否已注册
    if supabase:
        try:
            # 尝试查询用户是否已存在
            result = supabase.table('auth.users').select('email').eq('email', user_data.email).execute()
            if result.data:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="该邮箱已注册，请直接登录"
                )
        except Exception as e:
            logger.info(f"检查邮箱存在性时出错（可能是正常的）: {e}")
    
    # 临时存储用户注册信息
    temp_user_key = f"temp_user_{user_data.email}"
    verification_codes[temp_user_key] = {
        "username": user_data.username,
        "email": user_data.email,
        "password": user_data.password,
        "created_at": datetime.now()
    }
    
    # 生成并发送验证码
    verification_code = generate_verification_code()
    verification_codes[user_data.email] = {
        "code": verification_code,
        "expires_at": datetime.now() + timedelta(minutes=10),
        "attempts": 0
    }
    
    # 发送验证码邮件
    logger.info(f"📝 准备发送验证码邮件: {user_data.email}, 验证码: {verification_code}")
    email_sent = send_verification_email(user_data.email, verification_code)
    
    if email_sent:
        logger.info(f"✅ 用户注册信息已准备，验证码邮件发送成功: {user_data.email}")
    else:
        logger.error(f"❌ 用户注册信息已准备，但验证码邮件发送失败: {user_data.email}")
        # 即使邮件发送失败，也继续流程，让用户可以重新发送
    
    return {
        "message": "验证码已发送到您的邮箱",
        "email": user_data.email,
        "username": user_data.username,
        "verification_required": True,
        "expires_in": 600,  # 10分钟
        "verification_note": "请检查您的邮箱并输入6位数字验证码完成注册"
    }

@router.post("/verify-email", response_model=Dict[str, Any])
async def verify_email_and_complete_registration(verification_data: EmailVerificationConfirm):
    """验证邮箱验证码并完成注册"""
    email = verification_data.email
    code = verification_data.verification_code
    
    # 检查验证码是否存在
    if email not in verification_codes:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="验证码不存在或已过期，请重新发送"
        )
    
    verification_info = verification_codes[email]
    
    # 检查验证码是否过期
    if datetime.now() > verification_info["expires_at"]:
        del verification_codes[email]
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="验证码已过期，请重新发送"
        )
    
    # 检查尝试次数
    if verification_info["attempts"] >= 5:
        del verification_codes[email]
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="验证码尝试次数过多，请重新发送"
        )
    
    # 验证验证码
    if verification_info["code"] != code:
        verification_codes[email]["attempts"] += 1
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="验证码错误，请重新输入"
        )
    
    # 获取临时存储的用户信息
    temp_user_key = f"temp_user_{email}"
    if temp_user_key not in verification_codes:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="注册信息已过期，请重新注册"
        )
    
    user_info = verification_codes[temp_user_key]
    
    # 使用Supabase创建用户
    if not supabase:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="认证服务不可用"
        )
    
    try:
        logger.info(f"📝 验证码验证成功，开始创建用户: {email}")
        
        # 使用Supabase进行注册，禁用邮件确认
        response = supabase.auth.sign_up({
            "email": user_info["email"],
            "password": user_info["password"],
            "options": {
                "data": {
                    "username": user_info["username"],
                    "display_name": user_info["username"]
                },
                "email_confirm": False  # 禁用邮件确认，因为我们已经验证过了
            }
        })
        
        if not response.user:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="注册失败，请重试"
            )
        
        user = response.user
        logger.info(f"✅ 用户注册成功: {user.email} (ID: {user.id})")
        
        # 创建用户配置文件
        user_profile = await get_or_create_user_profile(
            user.id, 
            user.email, 
            user_info["username"]
        )
        
        # 清理临时数据
        del verification_codes[email]
        del verification_codes[temp_user_key]
        
        return {
            "message": "注册成功！",
            "user_id": user.id,
            "username": user_info["username"],
            "email": user.email,
            "email_confirmed": True,  # 通过验证码验证，视为已确认
            "verification_required": False
        }
        
    except AuthApiError as e:
        logger.error(f"❌ Supabase注册错误: {e}")
        error_message = str(e).lower()
        
        if "already registered" in error_message:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="该邮箱已注册，请直接登录"
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"注册失败: {str(e)}"
            )
    except Exception as e:
        logger.error(f"❌ 注册过程中发生错误: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="注册服务暂时不可用，请稍后再试"
        )

@router.post("/forgot-password")
async def forgot_password(email_data: dict):
    """发送密码重置邮件"""
    if not supabase:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="认证服务不可用"
        )
    
    email = email_data.get("email")
    if not email:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="邮箱地址不能为空"
        )
    
    try:
        logger.info(f"🔐 尝试发送密码重置邮件: {email}")
        
        # 使用Supabase发送密码重置邮件
        response = supabase.auth.reset_password_email(email)
        
        logger.info(f"✅ 密码重置邮件发送成功: {email}")
        
        return {
            "message": "密码重置邮件已发送",
            "email": email,
            "note": "请检查您的邮箱并点击重置链接来设置新密码"
        }
        
    except AuthApiError as e:
        logger.error(f"❌ Supabase密码重置错误: {e}")
        error_message = str(e).lower()
        
        if "user not found" in error_message or "not registered" in error_message:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="该邮箱未注册，请检查邮箱地址或先注册账户"
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="发送重置邮件失败，请重试"
            )
    except Exception as e:
        logger.error(f"❌ 发送密码重置邮件过程中发生错误: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="密码重置服务暂时不可用，请稍后再试"
        )

@router.get("/me", response_model=User)
async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
    """获取当前用户信息"""
    token = credentials.credentials
    logger.info(f"🔍 收到/me请求，令牌长度: {len(token) if token else 0}")
    
    # 首先尝试验证Supabase令牌
    if supabase:
        logger.info("🔐 尝试Supabase令牌验证...")
        supabase_user = verify_supabase_token(token)
        if supabase_user:
            logger.info(f"✅ Supabase验证成功: {supabase_user['email']}")
            user_profile = await get_or_create_user_profile(
                supabase_user["user_id"],
                supabase_user["email"]
            )
            return User(**user_profile)
        else:
            logger.warning("❌ Supabase令牌验证失败")
    else:
        logger.warning("⚠️ Supabase客户端不可用")
    
    # 降级到本地JWT验证
    logger.info("🔐 尝试本地JWT验证...")
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        user_id = payload.get("sub")
        email = payload.get("email")
        
        if user_id is None:
            logger.error("❌ JWT中缺少用户ID")
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="无效的认证令牌",
                headers={"WWW-Authenticate": "Bearer"},
            )
        
        logger.info(f"✅ 本地JWT验证成功: {email}")
        user_profile = await get_or_create_user_profile(user_id, email)
        return User(**user_profile)
        
    except jwt.PyJWTError as e:
        logger.error(f"❌ JWT验证失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的认证令牌",
            headers={"WWW-Authenticate": "Bearer"},
        )

@router.post("/logout")
async def logout(credentials: HTTPAuthorizationCredentials = Depends(security)):
    """用户登出"""
    if supabase:
        try:
            # 使用Supabase登出
            supabase.auth.sign_out()
            logger.info("✅ 用户已登出")
        except Exception as e:
            logger.error(f"登出过程中发生错误: {e}")
    
    return {"message": "登出成功"}

@router.put("/profile", response_model=User)
async def update_profile(
    preferences: Dict[str, Any],
    credentials: HTTPAuthorizationCredentials = Depends(security)
):
    """更新用户偏好设置"""
    token = credentials.credentials
    
    # 验证用户身份
    user_info = None
    if supabase:
        user_info = verify_supabase_token(token)
    
    if not user_info:
        try:
            payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
            user_info = {
                "user_id": payload.get("sub"),
                "email": payload.get("email")
            }
        except jwt.PyJWTError:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="无效的认证令牌"
            )
    
    if not user_info or not user_info.get("user_id"):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的认证令牌"
        )
    
    # 更新用户偏好
    if supabase:
        try:
            result = supabase.table('users').update({
                "preferences": preferences,
                "updated_at": datetime.now().isoformat()
            }).eq('id', user_info["user_id"]).execute()
            
            if result.data:
                user_data = result.data[0]
                return User(
                    user_id=user_data['id'],
                    email=user_data['email'],
                    username=user_data.get('display_name'),
                    created_at=user_data['created_at'],
                    preferences=user_data.get('preferences', {}),
                    display_name=user_data.get('display_name'),
                    avatar_url=user_data.get('avatar_url')
                )
        except Exception as e:
            logger.error(f"更新用户偏好失败: {e}")
    
    # 降级到基本响应
    user_profile = await get_or_create_user_profile(
        user_info["user_id"],
        user_info["email"]
    )
    user_profile["preferences"] = preferences
    return User(**user_profile)

@router.get("/health")
async def auth_health():
    """认证服务健康检查"""
    return {
        "status": "healthy",
        "supabase_available": supabase is not None,
        "timestamp": datetime.now().isoformat()
    }